import { constantRoutes } from '@/router'
// import { getRemoteRoutes } from '@/api/role';
import { setAsyncRoutes } from '@/router/async'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}
const mutations = {
  SET_ROUTES: (state1, routes) => {
    // 处理后端传来的路由
    setAsyncRoutes(routes)
    // 为了防止用户刷新页面导致动态创建的路由失效，将其存储在本地中
    // 这里见一个好用的 session 工具，vue-session，可直接安装，使用方式可以在 gitub 上搜索
    sessionStorage.setItem('menu', JSON.stringify(routes))
    // 将路由存储在 store 中
    state1.addRoutes = routes
    state1.routes = constantRoutes.concat(routes)
  }
}
const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, cat) => {
      try {
        commit('SET_ROUTES', roles)
        // getRemoteRoutes(roles).then((result) => {
        //   const accessedRoutes = result.data || [];
        //   console.log('routers', result);
        //   accessedRoutes.push({ path: '*', redirect: '/404', hidden: true });
        //   commit('SET_ROUTES', accessedRoutes);
        //   resolve(accessedRoutes);
        // });
      } catch (e) {
        cat(e)
      }
    })
  },
  appendRoutes({ commit }, accessedRoutes) {
    return new Promise(resolve => {
      accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
